import React, { Component } from 'react'
import { ListView, PullToRefresh } from 'antd-mobile'
import PropTypes from 'prop-types'
import ListViewItem from './listview_item'

// let pageIndex = 1
class MySecondListView extends Component {
    constructor(props) {
        super(props)
        
        this.state = {
            dataSource:this.props.dataSource,
            refreshing: true,
            isLoading: true,
            pageSize: 7,
            type:this.props.type,
            pageIndex:1
        }
    }

    static propTypes = {
        dataSource: PropTypes.any.isRequired,
        appendList: PropTypes.func.isRequired,
        type: PropTypes.string.isRequired
    }

    componentWillReceiveProps(nextProps){
        
        if (nextProps.dataSource !== this.props.dataSource){
            this.setState({
                dataSource: nextProps.dataSource,
                isLoading: false,
                refreshing: false,
                
            })
        }
    }


    onRefresh = () => {
        
        this.setState({ 
            refreshing: true, //显示加载的圆圈
            // isLoading: true
            pageIndex:1
        })
        this.props.appendList(this.state.type)//下拉刷新,只获取第一页
 
    }

    onEndReached = (event) => {
        // load new data
        // hasMore: from backend data, indicates whether it is the last page, here is false
    //    console.log(this.lv)
       
        this.setState({ 
            isLoading: true,
            pageIndex:this.state.pageIndex+1 
        })
        this.props.appendList(this.state.type, this.state.pageIndex)//下拉刷新，获取其他页内容
        
    }


    componentDidMount() {
        // this.props.refreshList()
        this.props.appendList(this.state.type,this.state.pageIndex)
    }

    render() {
        const row = (rowData, sectionID, rowID) => {
            return (
                <ListViewItem data={rowData} rowId={rowID} />
            )
        }
        return (
            <ListView
                ref={el => this.lv = el}
                initialListSize={this.state.pageSize} //初始加载数据pageSize条
                onEndReached={this.onEndReached}
                onEndReachedThreshold={20} //这个值越大越提早调用onEndReached
                pageSize={this.state.pageSize} //上拉加载数据，每次加载pageSize条，此值跟后台查询记录数要一致
                dataSource={this.state.dataSource}
                renderRow={row}
                renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                    {this.state.isLoading ? '加载中...' : '加载完'}
                </div>)}
                useBodyScroll={true}
                pullToRefresh={<PullToRefresh
                    refreshing={this.state.refreshing}
                    onRefresh={this.onRefresh}
                />}
            />
        )
    }
}

export default MySecondListView